<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>表单字段</title>
</head>
<body>
    <form  id="myForm">
        <label for="username">姓名</label>
        <input type="text" value="" name="username" id="username"/><br>
        <label for="usercode">编码</label>
        <input type="text" value="" name="usercode" id="usercode"/>
    </form>
    <form id="multiMyForm">
        <ul>
            <li><input type="radio" name="color" value="yellow"></li>
            <li><input type="radio" name="color" value="red"></li>
            <li><input type="radio" name="color" value="purpose"></li>
            <li><input type="radio" name="color" value="green"></li>
        </ul>
    </form>
</body>
<script>
    //单个 name 表单元素
    const myForm = document.getElementById("myForm");
    console.log('myForm.elements:',myForm.elements);//HTMLFormControlsCollection(2) [input#username, input#usercode, username: input#username, usercode: input#usercode]
    // 取得表单中的第一个字段
    let field1 = myForm.elements[0];
    console.log('field1:',field1);
    // 取得表单中 name 值为"usercode"的字段
    let field2 = myForm.elements['usercode'];
    console.log('field2:',field2);
    // 取得 form 字段的数量
    // 取得字段的数量
    let fieldCount = myForm.elements.length;
    console.log('fieldCount:',fieldCount);
    console.log('-------------------------------------------');
    //多个 name 相同表单元素
    const multiMyForm = document.getElementById('multiMyForm');
    console.log('multiMyForm.elements:',multiMyForm.elements); //multiMyForm.elements: HTMLFormControlsCollection(4) [input, input, input, input, color: RadioNodeList(4)] 不包含非表单元素。
    const colorFields = multiMyForm.elements["color"];
    console.log('colorFields:',colorFields);//colorFields: RadioNodeList(4) [input, input, input, input, value: '']
    let firstColorField = colorFields[0]; 
    let firstFormField = multiMyForm.elements[0];
    console.log(firstColorField === firstFormField);
</script>
</html>